<template>
  <view class="wrapper">
    <u-navbar class="my-title" title-size="32" :title="toUser.name"></u-navbar>
    <!-- 空盒子用来防止消息过少时 拉起键盘会遮盖消息 -->
    <view :animation="anData" style="height:0;">
    </view>
    <!-- 消息体 -->
    <!-- 用来获取消息体高度 -->
    <view id="msgList" class="msg-list">
      <!-- 消息 -->
      <view class="flex-column-start" v-if="msgList.length" v-for="(item, index) in msgList" :key="index">
        <view class="flex-row-start column-time">
          <!--  <view v-show="compareTime(index, item.createTime)" class="flex-row-start date-text"
            v-text="beautifyTime(item.createTime)">
          </view> -->
        </view>
        <!-- 用户消息 头像可选加入-->
        <view v-if="item.my" class="flex justify-end padding-right one-show  align-start  padding-top">
          <view class="flex justify-end" style="width: 400rpx;margin-top: 12px;">
            <view>
              <view class="user-name">{{ user.nickName }}</view>
              <view class="margin-left padding-chat bg-user-orang" style="border-radius: 35rpx; ">
                <text style="word-break: break-all;"
                      v-if="item.messageType === 'MESSAGE' && !emojistwo.includes(item.text)">{{ item.text }}</text>
                <view v-if="item.messageType === 'MESSAGE' && emojistwo.includes(item.text)"
                      v-html="textReplaceEmoji(item.text)"></view>


                <view v-if="item.messageType == 'GOODS'">
                  <view class="goods-card u-flex u-row-between u-p-b-0" style="width:100%;margin: 0 0; ">
                    <view class="image-box" @click="jumpGoodDesc(item)">
                      <image class="image" :src="JSON.parse(item.text)['thumbnail']" mode="widthFix"></image>
                    </view>
                    <view class="goods-desc" @click="jumpGoodDesc(item)">
                      <view class="goods-desc-name">
                        <text class="goods-card-goods-name">{{
                            JSON.parse(item.text)['goodsName']
                          }}</text>
                      </view>
                      <view class="goods-desc-rice" >￥{{
                          JSON.parse(item.text)['price'] | unitPrice
                        }}
                      </view>
                    </view>
                  </view>
                </view>

                <view v-if="item.messageType == 'ORDER'" @click="linkTosOrders(item.text)">
                  <view class="order-sn">
                    <div class="wes">订单号：{{ JSON.parse(item.text)['sn'] }}</div>
                    <div class='order-item flex' v-if="JSON.parse(item.text).orderItems.length"  v-for='(order,orderIndex) in JSON.parse(item.text).orderItems'>
                      <u-image  mode="widthFix" width='120rpx' height='120rpx' :src="order.image" />
                      <view class="name-or-time">
                        <div class="wes-2" >{{
                            order.name
                          }}</div>
                        <div class="main-color goods-desc-rice">{{
                            order.goodsPrice | unitPrice("￥")
                          }}</div>

                      </view>
                    </div>
                    <view class="order-list">
                      <view class="order-time">
                        <text>{{ JSON.parse(item.text)['paymentTime'] }}</text>
                      </view>
                    </view>
                  </view>
                </view>

                <!--                楼盘-->
                <view v-if="item.messageType === 'Build'">
                  <view class="goods-card u-flex u-row-between u-p-b-0" style="width:100%;margin: 0 0; ">
                    <view class="image-box" @click="jumpBuildDesc(building.id)">

                      <image class="image" :src="JSON.parse(item.text)['image']" mode="widthFix"></image>
                    </view>
                    <view class="goods-desc" @click="jumpBuildDesc(building.id)">
                      <view class="goods-desc-name">
                        <text class="goods-card-goods-name">{{
                            JSON.parse(item.text)['buildingName']
                          }}</text>
                      </view>
                      <view class="goods-desc-rice" >¥{{
                          JSON.parse(item.text)['price']
                        }}
                      </view>

                    </view>
                  </view>
                </view>

                <!--                房源-->
                <view v-if="item.messageType === 'House'">
                  <view class="goods-card u-flex u-row-between u-p-b-0" style="width:100%;margin: 0 0; ">
                    <view class="image-box" @click="jumpHouseDesc(JSON.parse(item.text)['id'])">
                      <image class="image" :src="JSON.parse(item.text)['faceUrl']" mode="widthFix"></image>
                    </view>
                    <view class="goods-desc" @click="jumpHouseDesc(JSON.parse(item.text)['id'])">
                      <view class="goods-desc-name">
                        <text class="goods-card-goods-name">{{
                            JSON.parse(item.text)['villageName']
                          }}</text>
                      </view>
                      <view class="goods-desc-rice" >¥{{
                          JSON.parse(item.text)['price']
                        }}
                      </view>
                    </view>
                  </view>
                </view>


                <view v-if="item.messageType == 'PHONE_NUMBER'">
                  <text>手机号：{{ item.text }}</text>
                </view>
                <!--                <view v-if="item.messageType == 'BIND_CONFIRMATION'">-->
                <!--                  <text>{{ item.text }}</text>-->
                <!--                </view>-->

                <!--              绑定关系-&#45;&#45;Confirmation  -->
                <view v-if="item.messageType === 'Confirmation'">
                  <view class="text-center mb-2" v-if="item.status!=1">是否接受  {{ JSON.parse(item.text)['agentName']}} 为您的专属经纪人？</view>
                  <view class="flex justify-around"  v-if="item.status!=1">
                    <!-- 修改此处样式 -->
                    <u-button @click="acceptRelation(JSON.parse(item.text))" style=" margin-right: 20rpx;">
                      确认
                    </u-button>
                    <u-button @click="rejectRelation()">拒绝</u-button>
                  </view>
                  <view class="flex justify-around" v-else>
                    <u-button style=" margin-right: 20rpx;">
                      <view class="text-center mb-2">{{  JSON.parse(item.text)['agentName']}}已接受成为 {{  JSON.parse(item.text)['villageName']}}的专属经纪人</view>

                    </u-button>

                  </view>
                </view>


              </view>
            </view>
          </view>
          <view>
            <u-avatar :src="user.face" :text="user.face ? '' : user.name" bg-color="#DDDDDD"></u-avatar>
          </view>
        </view>
        <!-- 接收人消息 -->
        <view v-else class="flex-row-start margin-left margin-top one-show">
          <view class="chat-img flex-row-center">
            <u-avatar :src="toUser.face" :text="toUser.face ? '' : toUser.name" bg-color="#DDDDDD">
            </u-avatar>
          </view>
          <view class="flex" style="width: 500rpx;">
            <view>
              <view class="other-name">{{ toUser.name }}</view>
              <view class="margin-left padding-chat flex-column-start bg-to-color" style="border-radius: 35rpx;">
                <text style="word-break: break-all;"
                      v-if="item.messageType === 'MESSAGE' && !emojistwo.includes(item.text)">{{ item.text }}</text>
                <view v-if="item.messageType === 'MESSAGE' && emojistwo.includes(item.text)"
                      v-html="textReplaceEmoji(item.text)"></view>

                <view v-if="item.messageType === 'GOODS'">
                  <view class="goods-card u-flex u-row-between u-p-b-0" style="width:100%;margin: 0 0; ">
                    <view class="image-box" @click="jumpGoodDesc(item)">
                      <image class="image" :src="JSON.parse(item.text)['thumbnail']" mode="widthFix"></image>
                    </view>
                    <view class="goods-desc" @click="jumpGoodDesc(item)">
                      <view class="goods-desc-name">
                        <text class="goods-card-goods-name">{{
                            JSON.parse(item.text)['goodsName']
                          }}</text>
                      </view>
                      <view class="goods-desc-rice" >¥{{
                          JSON.parse(item.text)['price']
                        }}
                      </view>
                    </view>
                  </view>
                </view>

                <view v-if="item.messageType === 'ORDER'">
                  <view class="order-sn">
                    <text>订单号：{{ JSON.parse(item.text)['sn'] }}</text>
                    <view class="order-list">
                      <img style="height: 120rpx; width: 120rpx; margin-top: 15rpx;"
                           :src="JSON.parse(item.text)['groupImages']" mode="widthFix" />
                      <view class="name-or-time">
                        <text @click="linkTosOrders(item.text)">{{
                            JSON.parse(item.text)['groupName']
                          }}</text>
                        <view class="order-time">
                          <text>{{ JSON.parse(item.text)['paymentTime'] }}</text>
                        </view>
                      </view>
                    </view>
                  </view>
                </view>

                <!--                楼盘-->
                <view v-if="item.messageType === 'Build'">
                  <view class="goods-card u-flex u-row-between u-p-b-0" style="width:100%;margin: 0 0; ">
                    <view class="image-box" @click="jumpBuildDesc(building.id)">
                        <image class="image" :src="JSON.parse(item.text)['image']" mode="widthFix"></image>
                    </view>
                    <view class="goods-desc" @click="jumpBuildDesc(building.id)">
                      <view class="goods-desc-name">
                        <text class="goods-card-goods-name">{{
                            JSON.parse(item.text)['buildingName']
                          }}</text>
                      </view>
                      <view class="goods-desc-rice" >¥{{
                          JSON.parse(item.text)['price']
                        }}
                      </view>
                    </view>
                  </view>
                </view>

                <!--             房源   -->
                <view v-if="item.messageType === 'House'">
                  <view class="goods-card u-flex u-row-between u-p-b-0" style="width:100%;margin: 0 0; ">
                    <view class="image-box" @click="jumpHouseDesc(JSON.parse(item.text)['id'])">
                      <image class="image" :src="JSON.parse(item.text)['faceUrl']" mode="widthFix"></image>
                    </view>
                    <view class="goods-desc" @click="jumpHouseDesc(JSON.parse(item.text)['id'])">
                      <view class="goods-desc-name">
                        <text class="goods-card-goods-name">{{
                            JSON.parse(item.text)['villageName']
                          }}</text>
                      </view>
                      <view class="goods-desc-rice" >¥{{
                          JSON.parse(item.text)['price']
                        }}
                      </view>
                    </view>
                  </view>
                </view>


                <!--              绑定关系-&#45;&#45;Confirmation  -->
                <view v-if="item.messageType === 'Confirmation'">
                  <view class="text-center mb-2"  v-if="item.status!=1">是否接受 {{  JSON.parse(item.text)['agentName']}} 为您的专属经纪人？</view>
                  <view class="flex justify-around"  v-if="item.status!=1">
                    <!-- 修改此处样式 -->
                    <u-button @click="acceptRelation(JSON.parse(item.text))" style=" margin-right: 20rpx;">
                     确认
                    </u-button>
                    <u-button @click="rejectRelation()">拒绝</u-button>
                  </view>
                  <view v-else>
                    <view class="text-center mb-2">{{  JSON.parse(item.text)['agentName']}}已接受成为 {{  JSON.parse(item.text)['villageName']}}的专属经纪人</view>
                  </view>
                </view>

              </view>
            </view>

          </view>
        </view>
      </view>
      <!-- 防止消息底部被遮 -->
      <view v-if="showHide && !localImGoodsId && showHideModel" class="flex-row-start margin-left margin-top"
            style="height: 180rpx;">
      </view>
      <!-- 如果没有聊天记录，定位到底部 -->
      <view
          :style="{ position:'fixed' , bottom:(inputHeight+66)+'px' , width:  '100%' }">
        <view class="cart-message" v-if="showHide && !localImGoodsId && showHideModel">
          <view class="goods-card u-flex u-row-between u-p-b-0">
            <view class="image-box" @click="jumpGoodDesc(item)">
              <image class="image" :src="goodListData.thumbnail" mode="widthFix"></image>
            </view>
            <view class="goods-desc" @click="jumpGoodDesc(item)">
              <view class="goods-desc-name">
                <text class="goods-card-goods-name">{{
                    goodListData.goodsName
                  }}</text>
              </view>
              <view class="goods-desc-rice" > ￥{{
                  goodListData.price | unitPrice
                }}
              </view>
            </view>
            <view class="cancel" @click="cancelModel">X</view>
            <view class="send-goods" @click="sendGoodsMessage">
              <view>发送商品</view>
            </view>
          </view>
        </view>
      </view>


      <!--    楼盘 -->
      <view
          :style="{ position:'fixed' , bottom:(inputHeight+66)+'px' , width:  '100%' }">
        <view class="cart-message" v-if="showBuildModel">
          <view class="goods-card u-flex u-row-between u-p-b-0">
            <view class="image-box" @click="jumpBuildDesc(building.id)">
              <image class="image" :src="JSON.parse(building.images)[0]" mode="widthFix"></image>
            </view>
            <view class="goods-desc" @click="jumpBuildDesc(building.id)">
              <view class="goods-desc-name">
                <text class="goods-card-goods-name">{{
                    building.buildingName
                  }}</text>
              </view>
              <view class="goods-desc-rice" > ￥{{
                  building.price
                }}
              </view>
            </view>
            <view class="cancel" @click="cancelBuildModel">X</view>
            <view class="send-goods" @click="sendBuildMessage">
              <view>发送楼盘</view>
            </view>
          </view>
        </view>
      </view>

      <!--  房源    -->
      <view
          :style="{ position:'fixed' , bottom:(inputHeight+66)+'px' , width:  '100%' }">
        <view class="cart-message" v-if="showHouseModel">
          <view class="goods-card u-flex u-row-between u-p-b-0">
            <view class="image-box" @click="jumpHouseDesc(house.id)">
              <image class="image" :src="house.faceUrl" mode="widthFix"></image>
            </view>
            <view class="goods-desc" @click="jumpHouseDesc(house.id)">
              <view class="goods-desc-name">
                <text class="goods-card-goods-name">{{
                    house.villageName
                  }}</text>
              </view>
              <view class="goods-desc-rice" > ￥{{
                  house.price
                }}
              </view>
            </view>
            <view class="cancel" @click="cancelHouseModel">X</view>
            <view class="send-goods" @click="sendHouseMessage">
              <view>发送房源</view>
            </view>
          </view>
        </view>
      </view>



      <!-- 防止消息底部被遮 -->
      <view style="height: 180rpx;">
      </view>
    </view>

    <view :style="{position: 'fixed',bottom:inputHeight+'px'}" class="flex-column-center"  :animation="animationData">
      <view class="bottom-dh-char flex-row-around" style="font-size: 55rpx;">
        <!-- vue无法使用软键盘"发送" -->
        <input @focus="inputBindFocus" @blur="eventHandle"  :adjust-position="false" v-model="msg" class="dh-input" type="text" style="background-color: #f0f0f0;" @confirm="sendMessage"
               confirm-type="send"  placeholder="用一句简短的话描述您的问题" />
        <view @click="sendMessage" class="cu-tag bg-main-color send round">
          发送
        </view>

        <!-- 新增十字按钮 -->
        <u-icon name="plus" @click="toggleFunctionButtons"></u-icon>

      </view>
      <!-- 底部导航栏 -->
      <view v-if="showFunctionButtons" class="function-buttons">
        <view @click="showPhoneConfirm" class="cu-tag  send round">
          发送手机号
        </view>
        <view @click="showBindConfirm" class="cu-tag  send round" >
          发送确认绑定
        </view>
      </view>


    </view>

    <!-- 自定义确认弹窗 - 发送手机号 -->
    <view v-if="showPhoneConfirmDialog" class="confirm-dialog">
      <view class="confirm-content">
        <text>是否确认发送手机号？</text>
        <view class="confirm-buttons">
          <view @click="sendPhoneNumber" class="confirm-button">确认</view>
          <view @click="hidePhoneConfirm" class="confirm-button">取消</view>
        </view>
      </view>
    </view>

    <!-- 自定义确认弹窗 - 发送确认绑定 -->
    <view v-if="showBindConfirmDialog" class="confirm-dialog">
<!--      <view class="confirm-content">-->
<!--        <text>是否确认发送确认绑定关联关系信息？</text>-->
<!--        <view class="confirm-buttons">-->
<!--          <view @click="sendBindConfirmation" class="confirm-button">确认</view>-->
<!--          <view @click="hideBindConfirm" class="confirm-button">取消</view>-->
<!--        </view>-->
<!--      </view>-->
<!--      -->

      <view class="confirm-content">
        <text v-if="bindOptions.length > 0">请确认绑定的房源</text>
        <view v-for="(option, index) in bindOptions" :key="index" @click="sendBindConfirmation(option)" class="confirm-button">
          {{ option.villageName }}
        </view>
        <view @click="hideBindConfirm" class="confirm-button" v-if="bindOptions.length > 0">取消</view>
        <text class="confirm-button" @click="hideBindConfirm" v-if="bindOptions.length ===0">暂无绑定房源</text>
      </view>

    </view>
  </view>
</template>

<script>
// rpx和px的比率
import UButton from "../../../uview-ui/components/u-button/u-button.vue";

var l
// 可用窗口高度
var wh
// 顶部空盒子的高度
var mgUpHeight
import {
  getTalkMessage,
  getTalkByUser,
  jumpObtain,
  bindConfirmation,
  getHouse,
  checkConfirmationCount
} from "@/api/im.js";
import SocketService from "@/utils/socket_service.js";
import storage from "@/utils/storage.js";
import {
  beautifyTime
} from "@/utils/filters.js"
import config from '@/config/config.js'
import { textReplaceEmoji, emojistwo } from '@/utils/emojis.js';
import { findBuildingById} from "@/api/building";
import {findHouseById} from "@/api/house.js";
import socketIO from '@/pages/mine/im/socket';
export default {
  components: {UButton},
  // 页面卸载后清除imGoodId
  onUnload () {
    // #ifdef H5
    uni.setStorageSync("imGoodId", '');
    // #endif

    if (this.socketOpen == true) {
      uni.closeSocket();
    }
  },
  onLoad (options) {

    //options.buildId  ---没有buildId则不显示 否则发送楼栋弹窗
    // if(undefined!==options.buildId){
    //   this.showBuildModel=true;
    // }else if(undefined!==options.houseId){
    //   this.showHouseModel=true
    // }

    this.showBuildModel=options.buildId
    this.showHouseModel=options.houseId;
    if(undefined!==options.buildId){


      findBuildingById(options.buildId).then(res=>{
        this.building=res.data.result;

      })
    }else if(undefined!==options.houseId){
      findHouseById({
        id: options.houseId
      }).then(res=>{
        this.house=res.data.data;
      })

    }


    // 没有goodsid则不显示 发送商品弹窗
    this.showHideModel = options.goodsid
    // 发送后刷新页面不显示 发送商品弹窗 local里面imGoodId不为空显示
    // #ifdef H5
    this.localImGoodsId = uni.getStorageSync("imGoodId");
    // #endif
    this.resolve = options
    // 请求商品信息
    if (this.resolve.goodsid) {
      this.commodityDetails()
    }
    // 如果需要缓存消息缓存msgList即可
    // 监听键盘拉起
    // 因为无法控制键盘拉起的速度,所以这里尽量以慢速处理
    // 监听键盘高度变化

    uni.onKeyboardHeightChange(res => {
      const query = uni.createSelectorQuery()
      query.select('#msgList').boundingClientRect(data => {
        // 若消息体没有超过2倍的键盘则向下移动差值,防止遮住消息体
        var up = res.height * 2 - data.height - l * 110
        if (up > 0) {
          // 动态改变空盒子高度
          this.messageBoxMove(up, 300)
          // 记录改变的值,若不收回键盘且发送了消息用来防止消息过多被遮盖
          mgUpHeight = up
        }
        // 收回
        if (res.height == 0) {
          this.messageBoxMove(0, 0)
        }
      }).exec();
    })
    var query = uni.getSystemInfoSync()

    l = query.screenWidth / 750
    wh = query.windowHeight
    this.scrollHeight = (query.windowHeight - 44) + "px"
    this.user = storage.getUserInfo()

    if(undefined!=options.userId){
      this.toUser.userId=options.userId
    }else{
      this.toUser = storage.getTalkToUser()
    }

    if (options.talkId) {
      this.params.talkId = options.talkId;
      this.getTalkMessage()
    } else {
      this.getTalk(options.userId)
    }

    // this.ws.connect();
    this.sokcet();


    //延时一秒执行
    setTimeout(() => {
      this.getHouse()
      //this.checkConfirmationCount();
    }, 1000);
  },
  // 页面隐藏
  onHide () {
    uni.closeSocket();
  },
  onUnload () {
    uni.closeSocket();
  },
  onPullDownRefresh () {
    this.params.pageNumber = this.params.pageNumber + 1
    this.getTalkMessage()
    setTimeout(function () {
      uni.stopPullDownRefresh();
    }, 1000);
  },

  data () {
    return {
      textReplaceEmoji,
      emojistwo,
      bindOptions: [],
      socketOpen: false, //是否连接
      storage,
      building:{},
      house:{},
      fixed: 'fixed',
      bottom: '50px',
      width: '100%',
      showHideModel: undefined,
      showBuildModel: undefined,
      showHouseModel: undefined,
      localImGoodsId: '',
      showHide: true,
      msgLoad: false,
      anData: {},
      animationData: {},
      msgList: [],
      oldHeight: 0,
      params: { //搜索条件
        talkId: '',
        pageSize: 10,
        pageNumber: 1,
      },
      goToIndex: 0, // 前往位置
      msg: "",
      go: 0,
      newMessageNum: 0,
      user: {},
      toUser: {},
      scrollHeight: 0,
      ws: new SocketService(),
      resolve: {},
      goodListData: {},
      count: 0, //判断socket断开连接请求次数
      inputHeight:0,
      showPhoneConfirmDialog: false,
      showBindConfirmDialog: false,
      showFunctionButtons: false,
      bingState:false,
      checkCount:false
    }
  },
  watch: {
    'ws.callBackMapping': {
      handler: function (val) {
        val = JSON.parse(val)
        if (val.messageResultType == 'MESSAGE') {
          this.msgList.push(val.result)
        }
        this.newMessageNum++;
        //接收到消息后发送已读
        let msg = val
        msg.operation_type = 'READ'
        this.ws.send(JSON.stringify(msg))
      }
    }
  },
  computed: {
    // 计算消息列表底部内边距
    msgListPaddingBottom() {
      const footerHeight = this.showFunctionButtons ? 160 : 80; // 功能按钮展开时的总高度
      return this.keyboardHeight > 0 ?
          `${this.keyboardHeight + footerHeight}rpx` :
          `${footerHeight}rpx`;
    }
  },
  methods: {
    // 处理键盘高度变化
    handleKeyboardChange(height) {
      this.keyboardHeight = height;
      this.$nextTick(() => {
        // 滚动到底部确保最新消息可见
        this.scrollToBottom();
      });
    },

    // 滚动到底部
    scrollToBottom() {
      uni.pageScrollTo({
        scrollTop: 99999,
        duration: 300
      });
    },

    // 切换功能按钮显示状态
    toggleFunctionButtons() {
      this.showFunctionButtons = !this.showFunctionButtons;
      this.$nextTick(() => {
        this.scrollToBottom();
      });
    },
    checkConfirmationCount(houseId){
      checkConfirmationCount(this.params.talkId).then(res=>{
        if(res.data.code==200){
          if(res.data.result<1){
            this.checkCount=true;
          }
        }
      })
    },
    getHouse(){
      getHouse(this.params.talkId).then(res=>{
        if(res.data.code==200){
          this.bindOptions=res.data.result
        }

      })
    },
    acceptRelation(item) {//acceptRelation 同意对方关系

      // 处理同意逻辑
      // console.log('同意对方关系', item);
      // uni.showToast({
      //   title: '已同意',
      //   icon: 'none'
      // });

      if (this.socketOpen == false) {
        console.info('socket未连接')
        return
      }

      console.info("==========="+item)

      //bindConfirmation    --接口
      bindConfirmation(this.params.talkId,item.id).then(res => {

        if(res.data.code==200){
          this.bingState=true;
          let msg = {
            operation_type: "MESSAGE",
            to: this.toUser.userId,
            from: this.user.id,
            message_type: "MESSAGE",
            context: "对方已同意",
            talk_id: this.params.talkId,
          };
          let data = JSON.stringify(msg);
          uni.sendSocketMessage({
            data: data,
          });
          this.msgList.push({
            "text": "对方已同意",
            "my": true,
            "messageType": 'MESSAGE'
          });
          let type = 'down';
          this.msgGo(type);

          this.showBindConfirmDialog = false;
           return;
        }
      });





    },
    rejectRelation(item) {
      console.log('拒绝对方关系', item);
      // 处理拒绝逻辑
      uni.showToast({
        title: '已拒绝',
        icon: 'none'
      });
      this.showBindConfirmDialog = false;
      // return;
    },
    toggleFunctionButtons() {
      this.showFunctionButtons = !this.showFunctionButtons;
    },
    // 其他方法保持不变
    showPhoneConfirm () {
      this.showPhoneConfirmDialog = true;
    },
    hidePhoneConfirm () {
      this.showPhoneConfirmDialog = false;
    },
    showBindConfirm () {
      // var house=this.house
      //   console.info("房源=="+house)
      // var  build=this.building
      // console.info("楼盘=="+build)
      //

      //查询是否发送过确认关系消息
      //
     ///
      // checkConfirmationCount(this.params.talkId).then(res=>{
      //   if(res.data.code==200){
      //     if(res.data.result<1){
      //       this.checkCount=true;
      //     }
      //   }
      // })
      this.showBindConfirmDialog = true;

      // if(this.checkCount){
      //   this.showBindConfirmDialog = true;
      // }else{
      //   uni.showToast({
      //     title: '您已发送确认邀请，请等待对方接收',
      //     icon: 'none'
      //   });
      // }

    },
    hideBindConfirm () {
      this.showBindConfirmDialog = false;
    },
    sendPhoneNumber () {
      this.showPhoneConfirmDialog = false;
      if (this.socketOpen == false) {
        return
      }
      // 假设手机号存储在 user.phone 中
      let phoneNumber = this.user.mobile;

      if (!phoneNumber) {
        uni.showToast({
          title: '未获取到手机号',
          icon: 'none'
        });
        return;
      }
      let msg = {
        operation_type: "MESSAGE",
        to: this.toUser.userId,
        from: this.user.id,
        message_type: "MESSAGE",
        context: phoneNumber,
        talk_id: this.params.talkId,
      };
      let data = JSON.stringify(msg);
      uni.sendSocketMessage({
        data: data,
      });
      this.msgList.push({
        "text": phoneNumber,
        "my": true,
        "messageType": 'MESSAGE'
      });
      let type = 'down';
      this.msgGo(type);
    },
    sendBindConfirmation (item) {////发送确认关系消息

      this.showBindConfirmDialog = false;
      if (this.socketOpen == false) {
        return
      }

      var houseId="id="+item.id;
      var  param={
        id:houseId,
        villageName:item.villageName,
        agentUserId:item.agentUserId,
        agentName:item.agentName
      }

      let msg = {
        operation_type: "MESSAGE",
        to: this.toUser.userId,
        from: this.user.id,
        message_type: "Confirmation",
        context: param,
        talk_id: this.params.talkId,
        status:0
      }

      let data = JSON.stringify(msg);
      console.log("发送消息======"+data)
      uni.sendSocketMessage({
        data: data
      });
      this.msgList.push({
        "text": JSON.stringify(param),
        "my": true,
        "messageType": 'Confirmation'
      })
      let type = 'down';
      this.msgGo(type)
      this.$nextTick(() => {
        uni.pageScrollTo({
          scrollTop: 2000000,
          duration: 300
        });
      })
      this.showBuildModel = false
    },
    eventHandle(){
      this.inputHeight = 0
    },
    inputBindFocus(e){
      if (e.detail.height) {
        this.inputHeight = e.detail.height //这个高度就是软键盘的高度
      }
    },
    sendMessage () {
    //  console.log("sendMessage"+this.msg+"==========="+this.socketOpen)
      if (this.msg == "") {
        return 0;
      }
      if (this.socketOpen == false) {
        return
      }
      let msg = {
        operation_type: "MESSAGE",
        to: this.toUser.userId,
        from: this.user.id,
        message_type: "MESSAGE",
        context: this.msg,
        talk_id: this.params.talkId,
      }
      let data = JSON.stringify(msg);
      console.log("发送消息======"+data)
      uni.sendSocketMessage({
        data: data,
      });
      this.msgList.push({
        "text": this.msg,
        "my": true,
        "messageType": 'MESSAGE'
      })
      let type = 'down';
      this.msgGo(type)
      this.msg = ""
    },
    sendGoodsMessage () {

      let msg = {
        operation_type: "MESSAGE",
        to: this.toUser.userId,
        from: this.user.id,
        message_type: "GOODS",
        context: this.goodListData,
        talk_id: this.params.talkId,
      }
      let data = JSON.stringify(msg);
      console.log("发送消息======"+data)
      uni.sendSocketMessage({
        data: data
      });
      this.msgList.push({
        "text": JSON.stringify(this.goodListData),
        "my": true,
        "messageType": 'GOODS'
      })
      this.showHide = false
      // #ifdef H5
      uni.setStorageSync("imGoodId", 1111111);
      // #endif
      this.$nextTick(() => {
        uni.pageScrollTo({
          scrollTop: 2000000,
          duration: 300
        });
      })
    },
    sendBuildMessage () {
      if(null!=this.building.images  || ''!=this.building.images){
        this.building.image=JSON.parse(this.building.images)[0]
      }

      let msg = {
        operation_type: "MESSAGE",
        to: this.toUser.userId,
        from: this.user.id,
        message_type: "Build",
        context: this.building,
        talk_id: this.params.talkId,
      }
      let data = JSON.stringify(msg);

      console.log("发送消息======"+data)
      uni.sendSocketMessage({
        data: data
      });
      this.msgList.push({
        "text": JSON.stringify(this.building),
        "my": true,
        "messageType": 'Build'
      })
      this.showBuildModel = false
      // #ifdef H5
      //   uni.setStorageSync("imGoodId", 1111111);
      // #endif
      this.$nextTick(() => {
        uni.pageScrollTo({
          scrollTop: 2000000,
          duration: 300
        });
      })
    },
    sendHouseMessage () {
      let msg = {
        operation_type: "MESSAGE",
        to: this.toUser.userId,
        from: this.user.id,
        message_type: "House",
        context: this.house,
        talk_id: this.params.talkId,
      }
      let data = JSON.stringify(msg);
      console.log("发送消息======"+data)
      uni.sendSocketMessage({
        data: data
      });
      this.msgList.push({
        "text": JSON.stringify(this.house),
        "my": true,
        "messageType": 'House'
      })
      this.showHouseModel = false
      // #ifdef H5
      //   uni.setStorageSync("imGoodId", 1111111);
      // #endif
      this.$nextTick(() => {
        uni.pageScrollTo({
          scrollTop: 2000000,
          duration: 300
        });
      })
    },
    sokcet () {

      var _this = this;
      uni.closeSocket();
      this.socketOpen = false;
      try {
        //WebSocket的地址
        var url = config.baseWsUrl + '/' + storage.getAccessToken();
        // 连接
        uni.connectSocket({
          url: url,
        });
        // 监听WebSocket连接已打开
        uni.onSocketOpen(function (res) {
          _this.socketOpen = true;
        });
        if (!this.socketOpen) {
          // 监听连接失败

          uni.onSocketError(function (err) {
            if (this.count < 3) {
              if (err && err.code != 1000) {
                _this.socketOpen = true;
                setTimeout(() => {
                  uni.connectSocket({
                    url: url,
                  });
                }, 2000)
              }
            } else {
              uni.closeSocket();
            }
            this.count++
          });
        }
        // 监听收到信息
        uni.onSocketMessage(function (res) {

          res.data = JSON.parse(res.data)
          if (res.data.messageResultType == 'MESSAGE') {
            _this.msgList.push(res.data.result)
            console.log(_this.msgList)
          }
          console.log(res.data)
          _this.msgGo()
        })
      } catch (e) {
        uni.closeSocket();
      }
      // 监听是否断线，断线进行重新连接
      uni.onSocketClose((res) => {
        if (res.code != null && res.code != 1000) {
          this.sokcet()
        }
      })
    },
    beautifyTime,
    //订单详情
    linkTosOrders (val) {
      let order = JSON.parse(val)
      uni.navigateTo({
        url: '/pages/order/orderDetail?sn=' + order.sn,
      });

    },
    // 跳转楼盘详情页
    jumpBuildDesc (id) {
      uni.navigateTo({
        url: `/pages/store/buildingDetail?id=`+id,
      });
    },
    jumpHouseDesc (id) {

      uni.navigateTo({
        url: `/pages/house/detail/detail?houseId=`+id,
      });
    },
    //跳转商品详情页
    jumpGoodDesc (item) {
      let info = JSON.parse(item.text)
      uni.navigateTo({
        url: `/pages/product/goods?id=${info.id}&goodsId=${info.goodsId}`,
      });
    },

    //取消发送
    cancelModel () {
      this.showHide = false
    },
    cancelBuildModel () {
      this.showBuildModel = false
    },
    cancelHouseModel () {
      this.showHouseModel = false
    },
    // 请求商品详情
    commodityDetails () {
      jumpObtain(this.resolve.skuid, this.resolve.goodsid).then((res) => {
        this.goodListData = res.data.result.data
      })
    },
    // 切换输入法时移动输入框(按照官方的上推页面的原理应该会自动适应不同的键盘高度-->官方bug)
    goPag (kh) {
      this.retractBox(0, 250)
      if (this.keyHeight != 0) {
        if (kh - this.keyHeight > 0) {
          this.retractBox(this.keyHeight - kh, 250)
        }
      }
    },
    // 移动顶部的空盒子
    messageBoxMove (x, t) {
      var animation = uni.createAnimation({
        duration: t,
        timingFunction: 'linear',
      })
      this.animation = animation
      animation.height(x).step()
      this.anData = animation.export()
    },
    // 保持消息体可见
    msgGo (type) {
      const query = uni.createSelectorQuery()
      // 延时100ms保证是最新的高度
      setTimeout(() => {
        // 获取消息体高度
        query.select('#msgList').boundingClientRect(data => {
          // 如果超过scorll高度就滚动scorll
          if (type == 'up') {
            this.go = data.height - this.oldHeight
          } else if (type == 'down') {
            this.go = data.height - wh + 120
          }
          // if (this.oldHeight > 0) {
          // 	this.go = data.height - this.oldHeight
          // } else {
          // 	// if (data.height - (wh - 32) > 0) {
          // 	this.go = data.height - wh + 120
          // }
          // 保证键盘第一次拉起时消息体能保持可见
          var moveY = wh - data.height
          // 超出页面则缩回空盒子
          if (moveY - mgUpHeight < 0) {
            // 小于0则视为0
            if (moveY < 0) {
              this.messageBoxMove(0, 200)
            } else {
              // 否则缩回盒子对应的高度
              this.messageBoxMove(moveY, 200)
            }
          }
          uni.pageScrollTo({
            scrollTop: this.go,
            duration: 0
          })
          this.oldHeight = data.height
        }).exec();
      }, 100)
    },
    // 回答问题的业务逻辑
    answer (id) {
      // 这里应该传入问题的id,模拟就用index代替了

    },
    // 不建议输入框聚焦时操作此动画
    ckAdd () {
      if (!this.showTow) {
        this.retractBox(-180, 350)
      } else {
        this.retractBox(0, 200)
      }
      this.showTow = !this.showTow
    },
    hideKey () {
      uni.hideKeyboard()
    },
    // 拉起/收回附加栏
    retractBox (x, t) {
      var animation = uni.createAnimation({
        duration: t,
        timingFunction: 'ease',
      })
      this.animation = animation
      animation.translateY(x).step()
      this.animationData = animation.export()
    },
    async getTalkMessage () {
      let type = '';
      await getTalkMessage(this.params).then(res => {

        if (res.data.success) {
          if (this.msgList.length >= 10) {
            this.msgList.unshift(...res.data.result)
            type = 'up'
          } else {
            this.msgList.unshift(...res.data.result)
            type = 'down'
          }
          this.msgList.forEach(item => {
            if (item.fromUser === this.user.id) {
              item.my = true
            }
          })
        }
      })
      console.log(this.msgList);
      this.msgGo(type)
    },
    // 上拉加载
    touchMoreMessage (e) {
      if (e.target.scrollTop == 0) {
        this.params.pageNumber = this.params.pageNumber + 1
        this.getTalkMessage()
      }
    },
    async getTalk (userId) {

      getTalkByUser(userId).then(res => {

        if (res.data.success) {

          this.toUser = res.data.result
          this.params.talkId = res.data.result.id
          this.getTalkMessage()
        }
      })
    },
    // 处理消息时间是否显示
    compareTime (index, datetime) {
      if (datetime == undefined) {
        return false;
      }
      if (typeof datetime == "number") {
        datetime = this.unixToDate(datetime, "yyyy-MM-dd hh:mm");
      }

      if (this.msgList[index].is_revoke == 1) {
        return false;
      }
      if (datetime) {
        datetime = datetime.replace(/-/g, "/");
      }

      let time = Math.floor(Date.parse(datetime) / 1000);
      let currTime = Math.floor(new Date().getTime() / 1000);

      // 当前时间5分钟内时间不显示
      if (currTime - time < 300) return false;
      // 判断是否是最后一条消息,最后一条消息默认显示时间
      if (index == this.msgList.length - 1) {
        return true;
      }
      let nextDate
      if (this.msgList[index + 1] && this.msgList[index + 1].createTime) {
        nextDate = this.msgList[index + 1].createTime.replace(/-/g, "/");
        if (nextDate - datetime < 300) return false;
      }

      return !(
          this.unixToDate(new Date(datetime), "{y}-{m}-{d} {h}:{i}") ==
          this.unixToDate(new Date(nextDate), "{y}-{m}-{d} {h}:{i}")
      );
    },

    /**
     * 将unix时间戳转换为指定格式
     * @param unix   时间戳【秒】
     * @param format 转换格式
     * @returns {*|string}
     */
    unixToDate (unix, format) {
      if (!unix) return unix;
      let _format = format || "yyyy-MM-dd hh:mm:ss";
      const d = new Date(unix);
      const o = {
        "M+": d.getMonth() + 1,
        "d+": d.getDate(),
        "h+": d.getHours(),
        "m+": d.getMinutes(),
        "s+": d.getSeconds(),
        "q+": Math.floor((d.getMonth() + 3) / 3),
        S: d.getMilliseconds(),
      };
      if (/(y+)/.test(_format))
        _format = _format.replace(
            RegExp.$1,
            (d.getFullYear() + "").substr(4 - RegExp.$1.length)
        );
      for (const k in o)
        if (new RegExp("(" + k + ")").test(_format))
          _format = _format.replace(
              RegExp.$1,
              RegExp.$1.length === 1 ?
                  o[k] :
                  ("00" + o[k]).substr(("" + o[k]).length)
          );
      return _format;
    },
  }
}
</script>

<style lang="scss" scoped>
.send{
  font-size: 24rpx !important;
}
.order-time {
  margin-top: 15rpx;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

.wrapper {
  height: auto !important;
}

.order-list {
  display: flex;
  color: black;
  font-size: 20rpx;
  font-weight: bold;
  width: 95%;
}

.order-sn {
  width: 350rpx;

}

.name-or-time {
  width: 200rpx;
  margin: 15rpx 15rpx;

}


.goods-card {
  border-radius: 20rpx;
  margin-top: 15rpx;
  background-color: #ffffff;
  padding-left: 12rpx;
  width: 95%;
  height: 120rpx;
  display: flex;
  flex-wrap: wrap;
  color: #302c2b;



  .image-box {
    width: 122rpx;
    height: 122rpx;
    overflow: hidden;

    .image {
      width: 122rpx;
      border-radius: 10rpx;
    }
  }

  .goods-desc {
    flex: 1;
    overflow: hidden;
    margin-left: 12rpx;
    width: 400rpx;

    .goods-desc-name {
      font-size: 30rpx;
      line-height: 1.5;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      margin-bottom: 20rpx;


      .goods-card-goods-name {
        color: black;
        text-overflow: ellipsis;
        font-size: 26rpx;
        font-weight: bold;
      }
    }

    .price {
      margin-top: 50rpx;
      line-height: 2;
      margin-left: 5px;
      font-size: 26rpx;
      font-weight: 700;
    }
  }

  .send-goods {
    color: #ffffff;
    height: 50rpx;
    width: 130rpx;
    background-color: #f21c0c;
    font-size: 28rpx;
    border-radius: 17rpx;
    text-align: center;
    line-height: 50rpx;
    padding: 0 10rpx;
    position: relative;
    top: 20rpx;
    right: 20rpx;
  }
}

.cancel {
  color: #737373;
  position: relative;
  bottom: 40rpx;
  left: 12%;
}

.cart-message {
  display: flex;
  justify-content: center;
  align-items: center;
}

.bottom-dh-char {
  background-color: #f9f9f9;
  width: 750rpx;
  height: 110rpx;
}

.user-name {
  text-align: right;
  font-size: 28rpx;
  color: #737373;
  margin-bottom: 10rpx;
  margin-right: 10rpx;
}

.other-name {
  text-align: left;
  font-size: 28rpx;
  color: #737373;
  margin-bottom: 10rpx;
  margin-left: 10rpx;
}
.dh-input {
  width: 500rpx;
  height: 65rpx;
  border-radius: 30rpx;
  padding-left: 15rpx;
  font-size: 22rpx;
  background-color: #FFFFFF;
}
.column-time {
  justify-content: center;
}



.chat-img {
  border-radius: 50%;
  width: 100rpx;
  height: 100rpx;
  background-color: #f7f7f7;
}

.padding-chat {
  padding: 17rpx 20rpx;
}

.tb-nv {
  width: 50rpx;
  height: 50rpx;
}
.goods-desc-rice{
  font-size: 28rpx;
  color: $main-color;
  font-weight: bold;
  margin-top: 10rpx;
}
.order-item{
  margin: 10rpx 0
}


uni-page-head {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 9999;
}

/* 确认弹窗的整体样式 */
.confirm-dialog {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
  padding: 20px;
  z-index: 1000;
}

/* 弹窗内容的样式 */
.confirm-content {
  text-align: center;
}

/* 弹窗中的文本样式 */
.confirm-content text {
  font-size: 16px;
  margin-bottom: 15px;
  display: block;
}

/* 确认按钮和取消按钮的容器样式 */
.confirm-buttons {
  display: flex;
  justify-content: space-around;
  margin-top: 15px;
}

/* 确认按钮和取消按钮的通用样式 */
.confirm-button {
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
}

/* 确认按钮的样式 */
.confirm-button:nth-child(1) {
  background-color: #007AFF;
  color: white;
}

/* 取消按钮的样式 */
.confirm-button:nth-child(2) {
  background-color: #ccc;
  color: black;
}

.function-buttons {
  display: flex;
  justify-content: space-around;
  background-color: #f9f9f9;
  padding: 10rpx;
  width: 100%; // 让容器宽度占满一行
}
</style>

<style lang="scss" scoped>
@import "./index-app.scss";
</style>
